import { defineStore } from "pinia";

interface UserInfo {
  username: string;
  token: string;
}

interface UserState {
  userInfo: any | null;
  isAuthenticated: boolean;
}

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    userInfo: null,
    isAuthenticated: false,
  }),

  actions: {
    async login(formData: any) {
      // 模拟登录请求
      return new Promise((resolve) => {
        setTimeout(() => {
          this.userInfo = {
            ...formData,
          };
          this.isAuthenticated = true;
          uni.setStorageSync("userInfo", JSON.stringify(this.userInfo));
          resolve(true);
        }, 1000);
      });
    },
    async getUserInfo() {
      return uni.getStorageSync("userInfo")
        ? JSON.parse(uni.getStorageSync("userInfo"))
        : null;
    },
    async setToken(token: string) {
      // 模拟登录请求
      return new Promise((resolve) => {
        this.isAuthenticated = true;
        uni.setStorageSync("token", token);
        resolve(true);
      });
    },
    async getToken() {
      return uni.getStorageSync("token");
    },
    logout() {
      this.userInfo = null;
      this.isAuthenticated = false;
      uni.removeStorageSync("userInfo");
      uni.removeStorageSync("token");
    },

    initialize() {
      const storedUser = uni.getStorageSync("userInfo");
      if (storedUser) {
        this.userInfo = storedUser;
        this.isAuthenticated = true;
      }
    },
  },
});
